/* 公用方法 */
import { baseurl } from "@/utils/constant";
import { useTableStore } from "@/stores/useTableStore";
// 自动适应浏览器高度
export function adaptiveHeight(height:number):number{
    return document.documentElement.clientHeight - height
}
// 数字转钱
export function numFormat(num:string){
    var c = num.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    return c;
}
// 获取url中的参数
import {type UrlInterface } from "@/utils/interface"
export function getUrlParams(){
    // 获取url中的参数
    let url    = new URLSearchParams(window.location.search)
    let params = <UrlInterface>{
        ut          : url.get('ut') || "",
        operationId : url.get('operationId') || "",
        loginid     : url.get('loginid') || "",
        token       : url.get('token') || "",
        shopId      : url.get('shopId') || "",
        merchantName: url.get('merchantName') || "",
        createType  : url.get('createType') || "",
    };
    // 假设当前URL为: https://www.example.com/?name=John&age=30
    return params;
}
// 验证是否为当日数据
export function validateDateDay(date:string) :boolean{
    let nowDate = new Date();
    let nowDay  = `${nowDate.getFullYear()}-${(nowDate.getMonth()+1).toString().padStart(2,'0')}-${nowDate.getDate().toString().padStart(2,'0')}`;
    return date !== nowDay;
}
// 两位数字补0
export function addZero(len:number,num:number):string{
    return num.toString().padStart(len,'0');
}
// 单条表格数据下载
export function downloadData(tradeId:string){
    const tableStore = useTableStore();
    let url = ''
    if(tableStore.detailType == 1){
        url = `${baseurl}/withdraw/getDownLoad?tradeId=${tradeId}`;
    }else{
        url = `${baseurl}/withdraw/getIncomeDownLoad?tradeId=${tradeId}`
    }
    console.log("下载表格数据:",tradeId);
    let a = document.createElement('a');
        a.href   = url;
        a.target = "_blank";
        a.click();
        a.remove()
} 
// 下载多条数据
export function downloadMoreData(){
    const tableStore = useTableStore();
    let arr :string[] = []
    tableStore.downloadList.forEach((item:any)=>{
        if(!!item.tradeId){
            arr.push(item.tradeId)
        }
    })
    downloadData(arr.join(','))
    console.log("下载多条数据:",arr.join(','));
}
// 时间最小范围
export function pickerOptions(time: Record<string, any>):boolean{
    if (!(time.getTime() > new Date().getTime())) {
        return time.getTime() < new Date("2023-07-14").getTime()
    }
    return false;
}
// 多选事件
export function handleSelectionChange(val:[]) {
    const tableStore = useTableStore();
    console.log("多选数据:",val);
    tableStore.downloadList    = val;
    tableStore.downloadBtnShow = tableStore.downloadList.length > 0
}
// 判断是否可选择
export function isSelectable(row:any) :Boolean{
    // 没有流水号不能下载
    if(!row['tradeId']){
        return false;
    }
    // 当天的信息不能下载
    if(row['startTime']){
        return validateDateDay(row['startTime'].split(' ')[0])
    }
    return true;
}
// 改变每页条数
export function handleSizeChange(val: number,func:any) {
    const tableStore = useTableStore();
    console.log(`改变每页条数: ${val}`)
    tableStore.pagination.currentPage = 1
    tableStore.pagination.pageSize = val
    func() // 回调函数
}
// 切换页码
export function handleCurrentChange(val: number,func:any) {
    const tableStore = useTableStore();
    console.log(`切换页码: ${val}`)
    tableStore.pagination.currentPage = val
    func() // 回调函数
}
// base64 转换为 file
export function base64ToFile(base64Url :string, filename :string) :File{
    // 获取到base64编码
    const arr = base64Url.split(',');
    const mime = (<string[]>arr[0].match(/:(.*?);/))[1];
    // 将base64编码转为字符串
    const bstr = atob(arr[1]);
    let n = bstr.length;
    // 创建初始化为0的，包含length个元素的无符号整型数组
    const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}
// 调用demo
// let file = base64ToFile(base64Data,projectName+'-'+id+".jpeg")
// //添加到input中
// let list = new DataTransfer();
// list.items.add(file);
// $("#files")[0].files = list.files